# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from functools import wraps


from google.appengine.api.datastore_types import GeoPt

import outusers
from lib.geomodel import Box, Point

from datastore.people import SiteUser,OutSiteUser

ROUTES_MEMCACHE_TIME = 8*60*60  # 8 hours for routes result
SIGNEL_ROUTE_MEMCACHE_TIME = 30*24*3600  # 30 days for one route

RIDERS_MEMCACHE_TIME = 8*60*60  # 8 hours for riders result
SIGNEL_RIDER_MEMCACHE_TIME = 30*24*3600  # 30 days for rider

MAX_COMMENT_LENGTH = 140

# see magicycle.js
def _S(obj, type="gmapLatLng"):
    if obj is not None:
        if type == "gmapLatLng":
            return "LL(%f,%f)"%(obj.lat,obj.lon)
        elif type == "LatLngBounds":
            return "LB(%f,%f,%f,%f)"%(obj.south_west.lat,obj.south_west.lon,
                                      obj.north_east.lat,obj.north_east.lon)
        else:
            return obj
    return obj

# see magicycle.js
def _US(data, pointtype=GeoPt):
    value = str(data)
    if value.startswith("LL("):
        value = value.replace("LL(", "").replace(")","")
        arr = value.split(",")
        return pointtype( float(arr[0]), float(arr[1]) )
    elif value.startswith == "LB(":
        value = value.replace("LB(", "").replace(")","")
        arr = value.split(",")
        return Box( float(arr[0]), float(arr[1]),
                    float(arr[2]), float(arr[3]) )
    else:
        return data

def unescape(string):
    return string and string.replace('&amp;', '&').replace('&lt;', '<').replace('&gt;', '>').replace('&quot;', '"').replace("&#39;", "")

def get_current_user():
    outsiteuser = outusers.get_outsite_user()
    if outsiteuser == None:
        return None
    return outsiteuser.Site_User

def check_site_user(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if get_current_user():
            return method(self, *args, **kwargs)
        return {"status": "error",
                "message": "you must login first"}
    return wrapper
